package com.realbrand.net.realbrandpay.ui.activity.shopcar;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.bean.ShopcarBean;
import com.realbrand.net.realbrandpay.inter.IReport;
import com.realbrand.net.realbrandpay.ui.activity.SetPersonImageActivity;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.ui.activity.login.LoginActivity;
import com.realbrand.net.realbrandpay.untils.Constant;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.util.L;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2017/8/24.
 */

public class ReportActivity extends BaseActivity {

    @BindView(R.id.report_toolBar)
    Toolbar reportToolBar;
    @BindView(R.id.report_cb_resonOne)
    AppCompatCheckBox reportCbResonOne;
    @BindView(R.id.report_cb_resonTwo)
    AppCompatCheckBox reportCbResonTwo;
    @BindView(R.id.report_cb_resonThree)
    AppCompatCheckBox reportCbResonThree;
    @BindView(R.id.report_cb_resonFour)
    AppCompatCheckBox reportCbResonFour;
    @BindView(R.id.report_cb_resonFive)
    AppCompatCheckBox reportCbResonFive;
    @BindView(R.id.report_et_reson)
    EditText reportEtReson;
    @BindView(R.id.report_et_adress)
    EditText reportEtAdress;
    @BindView(R.id.report_bt_report)
    Button reportBtReport;
    @BindView(R.id.report_iv_photoOne)
    ImageView reportIvPhotoOne;
    //举报的信息,商品码，门店名，门店地址，举报地址，截图
    private String commodityCode, userAccount, userAddress, reportAddress, screenShot;

    //举报理由
    private String reson;

    private String encode;

    private ShopcarBean bean;

    //上传的图片
    private Bitmap bitmapOne;

    //图片转换成字符串
    private String screenShotOne;

    private static final int PHONE_ONE = 0x0002;
    private static final int PHONE_TWO = 0x0003;
    private static final int PHONE_THREE = 0x0004;
    private String userName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        reportToolBar.setTitle("");
        reportToolBar.setNavigationIcon(R.mipmap.ic_back);
        setSupportActionBar(reportToolBar);
        reportToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //设置editText中hint的文本大小
        initHint();
        //获取举报对象
        bean = (ShopcarBean) getIntent().getExtras().getSerializable("report");
        //举报理由置空
        reson = "";
        if (LoginActivity.isLogin) {
            userName = getSharedPreferences(Constant.shareName, MODE_PRIVATE).getString("account", "zxy123");
        } else {
            userName = "anonymity";
        }
        setOnClick();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.report_activity;
    }

    @Override
    protected void setOnClick() {
        reportBtReport.setOnClickListener(this);
        reportIvPhotoOne.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //提交
            case R.id.report_bt_report:
                //举报问题
                StringBuilder problem = new StringBuilder();
                if (reportCbResonOne.isChecked()) {
                    problem.append(reportCbResonOne.getText().toString());
                }
                if (reportCbResonTwo.isChecked()) {
                    problem.append(reportCbResonTwo.getText().toString());
                }
                if (reportCbResonThree.isChecked()) {
                    problem.append(reportCbResonThree.getText().toString());
                }
                if (reportCbResonFour.isChecked()) {
                    problem.append(reportCbResonFour.getText().toString());
                }
                if (reportCbResonFive.isChecked()) {
                    problem.append(reportEtReson.getText().toString());
                }
                reson = problem.toString();
                commodityCode = bean.getScan();
                userAccount = bean.getStore();
                userAddress = bean.getAdress();
                reportAddress = reportEtAdress.getText().toString();
                //将图片转换成流
                if (bitmapOne != null) {
                    screenShotOne = Static.bitmapToString(bitmapOne);
                }
                if (TextUtils.isEmpty(problem)) {
                    Static.toast(ReportActivity.this, "请选择举报理由");
                } else {
                    if (TextUtils.isEmpty(reportAddress)) {
                        Static.toast(ReportActivity.this, "请输入举报地址");
                    } else {
                        report(commodityCode, userAccount, userAddress, reportAddress, screenShot, reson);
                    }
                }
                break;
            //上传图片
            case R.id.report_iv_photoOne:
                startActivityForResult(new Intent(ReportActivity.this, SetPersonImageActivity.class), PHONE_ONE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHONE_ONE:
                    bitmapOne = data.getParcelableExtra("bitmap");
                    Drawable drawableOne = new BitmapDrawable(bitmapOne);
                    reportIvPhotoOne.setImageDrawable(drawableOne);
                    break;
            }
        }
    }

    private void report(String commodityCode, String userAccount, String userAddress, String reportAddress, String screenShot, String reson) {
        ArrayList<String> keyList = new ArrayList<>();
        keyList.add("CommodityCode");
        keyList.add("UserAccount");
        keyList.add("UserAddress");
        keyList.add("ReportAddress");
        keyList.add("ReportProblem");
        keyList.add("ReportUser");
        ArrayList<String> valueList = new ArrayList<>();
        valueList.add(commodityCode);
        valueList.add(userAccount);
        valueList.add(userAddress);
        valueList.add(reportAddress);
        valueList.add(reson);
        valueList.add(userName);
        String string = Static.getString(keyList, valueList);
        try {
            encode = URLEncoder.encode(string, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("SOURCE", "ReportActivity");
            jsonObject.put("CREDENTIALS", "0");
            jsonObject.put("TERMINAL", "1");
            jsonObject.put("INDEX", Static.getDay());
            jsonObject.put("METHOD", "SubmitReportInfo");
            jsonObject.put("DATA", encode);
            jsonObject.put("Screenshot", screenShotOne);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, jsonObject.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.BASE_URL).build();
            IReport iReport = retrofit.create(IReport.class);
            Call<ResponseBody> report = iReport.report(body);
            report.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String result = response.body().string();
                        L.d(L.TAG, "举报返回" + result);
                        try {
                            JSONObject object = new JSONObject(result);
                            JSONArray data = object.getJSONArray("DATA");

                            String isSuccess = data.getJSONObject(0).getString("result");
                            if ("1".equals(isSuccess)) {
                                ReportActivity.this.finish();
                            } else if ("0".equals(isSuccess)) {
                                Static.toast(ReportActivity.this, "网络繁忙");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public void initHint() {
        // 新建一个可以添加属性的文本对象
        SpannableString ss = new SpannableString("请输入商店名称和地址");
        SpannableString spannableString = new SpannableString("请输入其它理由");
        // 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(12, true);
        // 附加属性到文本
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(ass, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        reportEtAdress.setHint(new SpannedString(ss));
        reportEtReson.setHint(new SpannedString(spannableString));
    }
}
